import { createRouter, createWebHistory } from "vue-router";
import type { RouteRecordRaw } from "vue-router";
import { useUserStore } from "@/stores/user";

// 路由配置
const routes: RouteRecordRaw[] = [
  {
    path: "/",
    name: "Layout",
    component: () => import("@/components/Layout.vue"),
    children: [
      {
        path: "",
        name: "Home",
        component: () => import("@/views/home/HomePage.vue"),
        meta: {
          title: "首页",
          requiresAuth: false,
        },
      },
      {
        path: "/library/:category?",
        name: "Library",
        component: () => import("@/views/novel/CategoryPage.vue"),
        meta: {
          title: "书库",
          requiresAuth: false,
        },
      },
      {
        path: "/vip",
        name: "VipInfo",
        component: () => import("@/views/vip/VipInfoPage.vue"),
        meta: {
          title: "VIP权益",
          requiresAuth: false,
        },
      },
      {
        path: "/demo/dialogs",
        name: "DialogDemo",
        component: () => import("@/views/demo/DialogDemo.vue"),
        meta: {
          title: "弹窗演示",
          requiresAuth: false,
        },
      },
      {
        path: "/novel/:id",
        name: "NovelDetail",
        component: () => import("@/views/novel/NovelDetail.vue"),
        meta: {
          title: "小说详情",
          requiresAuth: false,
        },
      },
      {
        path: "/search",
        name: "Search",
        component: () => import("@/views/novel/SearchPage.vue"),
        meta: {
          title: "搜索",
          requiresAuth: false,
        },
      },
      {
        path: "/ranking",
        name: "Ranking",
        component: () => import("@/views/novel/RankingPage.vue"),
        meta: {
          title: "排行榜",
          requiresAuth: false,
        },
      },
      {
        path: "/bookshelf",
        name: "Bookshelf",
        component: () => import("@/views/user/BookshelfPage.vue"),
        meta: {
          title: "书架",
          requiresAuth: true,
        },
      },
      {
        path: "/profile",
        name: "Profile",
        component: () => import("@/views/user/ProfilePage.vue"),
        meta: {
          title: "个人中心",
          requiresAuth: true,
        },
      },
      {
        path: "/wallet",
        name: "Wallet",
        component: () => import("@/views/user/WalletPage.vue"),
        meta: {
          title: "我的钱包",
          requiresAuth: true,
        },
      },
      {
        path: "/admin/users",
        name: "UserManage",
        component: () => import("@/views/admin/UserManagePage.vue"),
        meta: {
          title: "用户管理",
          requiresAuth: true,
        },
      },
      {
        path: "/admin/user-data",
        name: "UserDataManage",
        component: () => import("@/views/admin/UserDataManagePage.vue"),
        meta: {
          title: "用户数据管理",
          requiresAuth: true,
        },
      },
    ],
  },
  {
    path: "/reader/:novelId/:chapterId",
    name: "Reader",
    component: () => import("@/views/reader/ReaderPage.vue"),
    meta: {
      title: "阅读器",
      requiresAuth: false,
      hideHeader: true,
    },
  },
  {
    path: "/auth",
    name: "Auth",
    component: () => import("@/views/auth/AuthLayout.vue"),
    children: [
      {
        path: "login",
        name: "Login",
        component: () => import("@/views/auth/LoginPage.vue"),
        meta: {
          title: "用户登录",
          requiresAuth: false,
        },
      },
      {
        path: "register",
        name: "Register",
        component: () => import("@/views/auth/RegisterPage.vue"),
        meta: {
          title: "用户注册",
          requiresAuth: false,
        },
      },
      {
        path: "forgot-password",
        name: "ForgotPassword",
        component: () => import("@/views/auth/ForgotPasswordPage.vue"),
        meta: {
          title: "忘记密码",
          requiresAuth: false,
        },
      },
      {
        path: "reset-password",
        name: "ResetPassword",
        component: () => import("@/views/auth/ResetPasswordPage.vue"),
        meta: {
          title: "重置密码",
          requiresAuth: false,
        },
      },
    ],
  },
  {
    path: "/:pathMatch(.*)*",
    name: "NotFound",
    component: () => import("@/views/NotFound.vue"),
    meta: {
      title: "页面未找到",
    },
  },
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    } else {
      return { top: 0 };
    }
  },
});

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore();

  if (import.meta.env.DEV) {
    console.log("路由守卫:", {
      to: to.path,
      from: from.path,
      isLoggedIn: userStore.isLoggedIn,
      user: userStore.user?.email,
      requiresAuth: to.meta.requiresAuth,
      isInitialized: userStore.isInitialized,
    });
  }

  // 检查是否需要登录
  if (to.meta.requiresAuth && !userStore.isLoggedIn) {
    if (import.meta.env.DEV) {
      console.log("需要登录，重定向到登录页");
    }
    // 保存原始路径，登录后跳转回来
    const redirect = to.fullPath;
    next({
      name: "Login",
      query: { redirect },
    });
    return;
  }

  // 如果已登录用户访问登录/注册页面，重定向到首页
  if ((to.name === "Login" || to.name === "Register") && userStore.isLoggedIn) {
    if (import.meta.env.DEV) {
      console.log("已登录用户访问登录页，重定向到首页");
    }
    next({ name: "Home" });
    return;
  }

  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 海外文学网`;
  }

  // 确保路由能够正常进行
  next();
});

export default router;
